package org.extblog.wkm.web.service.article.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.extblog.wkm.web.dao.article.ArticleDao;
import org.extblog.wkm.web.service.AbstractService;
import org.extblog.wkm.web.service.article.ArticleService;
import org.extblog.wkm.web.util.DateFormatPattern;
import org.extblog.wkm.web.vo.ArticleView;
import org.springframework.stereotype.Component;

@Component
public class ArticleServiceImpl extends AbstractService implements
		ArticleService {

	private ArticleDao articleDao = null;
	
	public ArticleDao getArticleDao() {
		return articleDao;
	}
	@Resource
	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}

	@Override
	public boolean addArticle(ArticleView articleView) {
		// TODO Auto-generated method stub
		articleView.setArticleId(DateFormatPattern.ID + DateFormatPattern.SPLIT_CHAR + DateFormatUtils.format(Calendar.getInstance(),DateFormatPattern.DATE_TIME));
		int count = articleDao.insertArticle(articleView);
		return count >= 0;
	}

	@Override
	public boolean deleteArticle(ArticleView articleView) {
		// TODO Auto-generated method stub
		int count = articleDao.deleteBody(articleView);
		return count >= 0;
	}

	@Override
	public boolean updateArticle(ArticleView articleView) {
		// TODO Auto-generated method stub
		int count = articleDao.updateArticle(articleView);
		return count >= 0;
	}

	@Override
	public List<ArticleView> loadArticle(ArticleView articleView) {
		// TODO Auto-generated method stub
		List<Map<String, String>> list = articleDao.selectArticle(articleView.getArticleId());
		List<ArticleView> result = new ArrayList<ArticleView>();
		
		if(list == null){
			return result;
		}
		
		try{
			for (Map<String, String> map : list){
				ArticleView temp = new ArticleView();
				BeanUtils.populate(temp, map);
				result.add(temp);
			}
		} catch (IllegalAccessException e){
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (InvocationTargetException e){
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return result;
	}

}
